<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="tree"
          node-key="id"
          highlight-current
          :expand-on-click-node="false"
          default-expand-all
          :data="depts"
          :props="defaultProps"
          @current-change="selectNodeChange"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportEmployExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list" style="width: 100%;">
          <el-table-column width="80" prop="staffPhoto" label="头像">
            <template #default="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username?.charAt(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column width="80" prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" />
          <el-table-column prop="workNumber" label="工号" />
          <el-table-column prop="formOfEmployment" label="录用形式">
            <template #default="{ row }">
              <span>{{ row.formOfEmployment === 1 ? '正式' : '非正式' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="departmentName" label="入职时间" />
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button type="text" size="mini" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="mini" style="margin-right: 10px;" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm title="确认删除吗" @onConfirm="btnRowEdit(row.id)">
                <el-button slot="reference" type="text" size="mini">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <!-- 分页 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px;">
          <el-pagination
            layout="total,prev, pager, next"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            :total="total"
            @current-change="currentPage"
          />
        </el-row>
      </div>
      <!-- 分配权限弹层 -->
      <el-dialog title="分配权限" :visible.sync="showRoleDialog">
        <el-checkbox-group v-model="roleIds">
          <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
            {{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
        <el-button type="primary" @click="confirmRole">确认</el-button>
        <el-button>取消</el-button>
      </el-dialog>
    </div>
    <importExcel :upload-success="getEmployList" :show-excel-dialog.sync="showExcelDialog" />
  </div>
</template>

<script>
import { getDepartmentList } from '@/api/department'
import { translateListToTreeData } from '@/utils'
import { getEmployList, exportEmployee, delEmployee, getRoleListByState, getEmployInfo, assignRoles } from '@/api/employ'
import FileSaver from 'file-saver'
import importExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: {
    importExcel
  },
  data() {
    return {
      currentUserId: null,
      roleIds: [], // 角色id
      roleList: [], // 角色列表
      showRoleDialog: false, // 分配权限弹层
      showExcelDialog: false, // excel弹层
      list: [], // 存储员工个人信息列表
      depts: [
      ],
      defaultProps: {
        children: 'children',
        label: 'name' // 标签文本字段
      },
      queryParams: {
        departmentId: null, // 部门Id
        page: 1, // 当前页码
        pagesize: 5, // 每页条数
        keyword: ''
      },
      total: 0 // 总条数
    }
  },
  created() {
    this.getDepartmentList()
    this.getEmployList()
  },
  methods: {
    // 角色点击按钮
    async btnRole(id) {
      // // 1.显示弹层
      // this.showRoleDialog = true
      // 2.获取请求角色列表
      const res = await getRoleListByState()
      console.log(res)
      // 3.渲染数据
      this.roleList = res
      // 4.获取到员工所拥有的角色信息 - 根据员工的Id
      this.currentUserId = id
      const { roleIds } = await getEmployInfo(id)
      console.log(roleIds)
      // 5.渲染，赋值给选中的角色列表
      this.roleIds = roleIds
      // 6.问题：加载不完全，解决：最后加载弹层
      this.showRoleDialog = true
    },
    // 点击角色确认按钮
    async confirmRole() {
      // 调用接口
      // const res = await assignRoles({
      //   id: this.currentUserId,
      //   roleIds: this.roleId
      // })
      // console.log(res)
      await assignRoles({
        id: this.currentUserId,
        roleIds: this.roleIds
      })
      this.$message.success('分配角色成功')
      this.showRoleDialog = false
    },
    // 删除员工
    async btnRowEdit(id) {
      console.log(id)
      await delEmployee(id)
      // console.log(res)
      if (this.list.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      this.$message.success('删除成功')
      // 重新加载数据
      this.getEmployList()
    },
    // 批量导出excel
    async exportEmployExcel() {
      console.log('批量导出')
      const res = await exportEmployee()
      console.log(res)
      FileSaver.saveAs(res, '员工数据.xlsx')
    },
    changeValue() {
      // 防抖
      let timer = null
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployList()
      }, 1000)
    },
    currentPage(newPage) {
      this.queryParams.page = newPage // 赋值当前页码
      this.getEmployList()
    },
    // 获取员工列表
    async getEmployList() {
      // console.log('获取员工个人')
      const { rows, total } = await getEmployList(this.queryParams)
      // console.log(rows)
      this.list = rows
      this.total = total
    },
    // 获取部门列表
    async getDepartmentList() {
      const res = await getDepartmentList()
      // console.log(res)
      this.depts = translateListToTreeData(res, 0)
      // 记录部门列表
      this.queryParams.departmentId = this.depts[0].id
      console.log(this.depts)
      // 设置收个节点的选中状态
      // 树形组件的渲染
      this.$nextTick(() => {
        // 目的：为了保证属性组件渲染完成们才能进行节点的选择设置
        this.$refs.tree.setCurrentKey(this.queryParams.departmentId)
      })
    },
    // 切换节点
    selectNodeChange(node) {
      // console.log(node)
      this.queryParams.departmentId = node.id
      // this.queryParams.page = 1
      this.getEmployList()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    flex: 1;
    padding: 20px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
